<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/3/13
 * Time: 11:16
 */

namespace App\Http\Controllers\Api\Open;


use App\Http\Resources\CommentCollection;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CommentController extends BaseController
{
    public function index()
    {
        $user = $this->getUser();
        $liveroom = $user->liveroom;
        $page = $liveroom->comments()->with([
            'user',
            'commentable'
        ])->orderBy('id', 'desc')->paginate();


        $data = CommentCollection::make($page);

        return $this->success($data);
    }

    public function replay(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'id' => 'required',
            'content' => ['required']
        ],[
            'content.required'=>'请输入回复内容'
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $id = $this->getId();
        $user = $this->getUser();
        $comment = Comment::query()->where('liveroom_id', $user->liveroom->id)->with([
            'user',
            'commentable'
        ])->findOrFail($id);
        $comment->c_replay = $request->input("content");
        $comment->save();
        $row = \App\Http\Resources\Comment::make($comment);
        return $this->success($row);
    }


    public function manage(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'id' => 'required',
            'mode' => ['required', Rule::in(['jx', 'zd', 'sc'])]
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $id = $this->getId();
        $user = $this->getUser();
        $comment = Comment::query()->where('liveroom_id', $user->liveroom->id)->with([
            'user',
            'commentable'
        ])->findOrFail($id);
        switch ($request->input("mode")) {
            case 'jx':
                if ($comment->is_hot == 1) {
                    $comment->is_hot = 0;
                    $comment->stick = 0;
                } else {
                    $comment->is_hot = 1;
                }
                $comment->save();
                $row = \App\Http\Resources\Comment::make($comment);
                break;
            case 'zd':
                if ($comment->stick > 0) {
                    $comment->is_hot = 0;
                    $comment->stick = 0;
                } else {
                    $comment->is_hot = 1;
                    $comment->stick = 1;
                }
                $comment->save();
                $row = \App\Http\Resources\Comment::make($comment);
                break;
            case 'sc':
                $comment->delete();
                $row = [];
                break;
        }

        return $this->success($row);

    }


}